package com.rzjm.api.service.impl;

import com.rzjm.api.dao.SplitAccountMapper;
import com.rzjm.api.dao.SplitAccountRecordMapper;
import com.rzjm.api.dao.WxUserCashRecordMapper;
import com.rzjm.api.entity.*;
import com.rzjm.api.exception.TransactionalException;
import com.rzjm.api.pay.wxpay.WxAppPay;
import com.rzjm.api.service.SplitAccountService;
import com.rzjm.api.service.WxUserCashRecordService;
import com.rzjm.api.util.MathUtil;
import com.rzjm.api.util.OrderUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

@Service
public class WxUserCashRecordServiceImpl extends BaseServiceImpl<WxUserCashRecordMapper, WxUserCashRecord> implements WxUserCashRecordService {

    @Resource
    private WxUserCashRecordMapper cashRecordMapper;
    @Resource
    private SplitAccountRecordMapper splitAccountRecordMapper;
    @Resource
    private SplitAccountMapper splitAccountMapper;
    @Resource
    private SplitAccountService splitAccountService;

    @Value("${web.appid}")
    private String appid;
    @Value("${web.appidMp}")
    private String appidMp;
    @Value("${web.secret}")
    private String secret;
    @Value("${web.mch_id}")
    private String mch_id;
    @Value("${web.api_key}")
    private String api_key;
    @Value("${web.keyPath}")
    private String keyPath;//微信支付的回调地址


    @Override
    @Transactional
    public int addRecord(User user, UserMp userMp, double payMoney, SplitAccount splitAccount) {
        int ret = 0;
        try{
            String tradeNo = OrderUtil.getPayNo();
            WxUserCashRecord cashRecord = new WxUserCashRecord();
            cashRecord.setPartnerTradeNo(tradeNo);
            cashRecord.setCreateTime(new Date());
            cashRecord.setUserId(user.getId());
            cashRecord.setMpOpenId(userMp.getOpenId());
            cashRecord.setPayMoney(new BigDecimal(payMoney));
            cashRecord.setMchId(mch_id);
            cashRecord.setMchAppid(appid);
            cashRecord.setRemark("提现到零钱");
            cashRecord.setPayState(0);
            cashRecord.setPayTime(new Date());
            ret = cashRecordMapper.insert(cashRecord);
            if(ret <= 0){
                throw new TransactionalException("cashRecordMapper insert error");
            }

            int status = 0;
            WxAppPay wxAppPay = new WxAppPay("", secret, appidMp, mch_id,api_key);
            Map<String, String> retRequest = wxAppPay.weixinChangePay(cashRecord.getPartnerTradeNo(),cashRecord.getPayMoney(),cashRecord.getMpOpenId(),keyPath);
            if(retRequest.containsKey("return_code")){
                String return_code = retRequest.get("return_code");
                if(return_code.equals("SUCCESS")){
                    cashRecord.setPayState(1);//支付成功
                    status = 1;
                }else{
                    cashRecord.setPayState(2);//支付成功
                }
                String pay_str = retRequest.get("pay_str");
                String reback_str = retRequest.get("reback_str");
                cashRecord.setPayStr(pay_str);
                cashRecord.setRebackStr(reback_str);
            }

            ret = cashRecordMapper.updateById(cashRecord);
            if(ret <= 0){
                throw new TransactionalException("cashRecordMapper updateById error");
            }

            if(status == 1){
                double totalAmount = splitAccount.getSplitMoney().doubleValue();
                totalAmount = MathUtil.getDoubleUp(totalAmount - payMoney);
                splitAccount.setSplitMoney(new BigDecimal(totalAmount));
                ret = splitAccountMapper.updateById(splitAccount);
                if(ret <= 0){
                    throw new TransactionalException("splitAccountRecordMapper insert error");
                }

                SplitAccountRecord splitAccountRecord = new SplitAccountRecord();
                splitAccountRecord.setUserId(user.getId());
                splitAccountRecord.setCreateTime(new Date());
                //动账类型  0 - 提现 1 - 重置  2 - 分成增加
                splitAccountRecord.setFromType(0);
                //1 - 进账  0 - 出账
                splitAccountRecord.setInOrOut(0);
                splitAccountRecord.setRemark("用户发起提现" );
                splitAccountRecord.setSplitMoney(new BigDecimal(payMoney));
                ret = splitAccountRecordMapper.insert(splitAccountRecord);
                if(ret <= 0){
                    throw new TransactionalException("splitAccountRecordMapper insert error");
                }
            }

            return ret;
        }catch (Exception e){
            e.printStackTrace();
            throw new TransactionalException("splitAccountRecordMapper insert error");
        }
    }
}
